package com.adgroup.doremon_ad;

import java.text.SimpleDateFormat;
import java.util.Date;

import model.User;

import org.json.JSONException;
import org.json.JSONObject;

import util.Config;
import util.Utility;
import adapter.JsonParse;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import database.Database;

public class UpdateInforActivity extends SherlockFragmentActivity{

	private DisplayMetrics metrics;
	private LinearLayout menuPanel;
	private int panelWidth;
	private LinearLayout slidingPanel; 
	private boolean isExpanded;

	FrameLayout.LayoutParams menuPanelParameters;
	FrameLayout.LayoutParams slidingPanelParameters;
	LinearLayout.LayoutParams headerPanelParameters;
	LinearLayout.LayoutParams listViewParameters;
	
	//views
	EditText etnickname;
	EditText etPass;
	EditText etRePass;
	CheckBox chkMale;
	CheckBox chkFemale;
	TextView tvBirthday;
	StringBuilder sBirthday;
	LinearLayout linearRoot;
	ImageButton btnBirthday;
	Button btnRegister;
	Spinner spinner;
	ProgressBar progressWaiting;
	ImageView ivAvatar;
	
	private int mYear;
	private int mMonth;
	private int mDay;
	private int logoid = 0;
	private String gcmId = "";
	private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
	ProgressDialog progress;
	Handler handler = new Handler();
	LinearLayout root;
	User u;

	String retype;
	
	private ActionBar mActionBar;
	private View v;
	int page = 1;
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
		case android.R.id.title:
			finish();
			break;		
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@SuppressLint({ "CutPasteId", "NewApi" })
	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.updateinfor);
		 AdView mAdView = (AdView) this.findViewById(R.id.adView);
		    AdRequest adRequest = new AdRequest.Builder().build();
		    mAdView.loadAd(adRequest);
		    
		//action bar
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setDisplayUseLogoEnabled(true);
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setTitle(getResources().getString(R.string.actionbar_update));
		mActionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.background_actionbar));
		
		metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		
		//set up
		panelWidth = (int) ((metrics.widthPixels) * 0.6);
		menuPanel = (LinearLayout) findViewById(R.id.menuPanelUpdate);
		menuPanelParameters = (FrameLayout.LayoutParams) menuPanel
				.getLayoutParams();
		menuPanelParameters.width = panelWidth;
		menuPanel.setLayoutParams(menuPanelParameters);
		slidingPanel = (LinearLayout) findViewById(R.id.slidemainupdate);
		slidingPanelParameters = (FrameLayout.LayoutParams) slidingPanel
				.getLayoutParams();
		slidingPanelParameters.width = metrics.widthPixels;
		slidingPanel.setLayoutParams(slidingPanelParameters);

		
		//mapping
		tvBirthday = (TextView) findViewById(R.id.txtbirthdayfillUpdate);
		chkFemale = (CheckBox) findViewById(R.id.checkfemaleUpdate);
		chkMale = (CheckBox) findViewById(R.id.checkmaleUpdate);
		etnickname = (EditText) findViewById(R.id.editTextNickNameUpdate);
		etPass = (EditText) findViewById(R.id.editTextPasswordUpdate);
		etRePass = (EditText) findViewById(R.id.editTextRePassWordUpdate);
		linearRoot = (LinearLayout) findViewById(R.id.slidemainupdate);
		btnBirthday = (ImageButton) findViewById(R.id.btnbirthdayUpdate);
		btnRegister = (Button) findViewById(R.id.btnregisterUpdate);
		spinner = (Spinner) findViewById(R.id.spinneruserlogoUpdate);
		progressWaiting =(ProgressBar) findViewById(R.id.progressBarwaitinguserlogoUpdate);
		root = (LinearLayout) findViewById(R.id.rootregisterUpdate);
		
		//set data user
		u = new Database(UpdateInforActivity.this).getUser();
		if(u!=null){ 
			String as = u.getBirthday();
			String[] birth = u.getBirthday().split("-");
			try{
				mYear = Integer.parseInt(birth[0]);
				mMonth = Integer.parseInt(birth[1]);;
				mDay = Integer.parseInt(birth[2]);;
			}
			catch(Exception ex){
				mYear = 1991;
				mMonth = 11;
				mDay = 1;
			}
			tvBirthday.setText(u.getBirthday());
			etnickname.setText(u.getNickName());
			if(u.getGender().equalsIgnoreCase("1")){
				chkMale.setChecked(true);
			}
			else{
				chkFemale.setChecked(true);
			}
			
		}
		//set adapter
		root.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				try {
					imm.hideSoftInputFromWindow(etPass.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etRePass.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etnickname.getWindowToken(), 0);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		});
		
		//register gcm id
		//new AsynGetGCMID().execute();
		
		//GCMRegistrar.checkDevice(this);
		/*GCMRegistrar.checkManifest(this);
		// Get GCM registration id
		gcmId = GCMRegistrar.getRegistrationId(this);
		GCMRegistrar.setRegisterOnServerLifespan(getApplicationContext(),
				604800000);	 
		if (gcmId.equals("")) {
			GCMRegistrar.register(this, Configuration.SENDERID);
		} else {
			long limittime = GCMRegistrar.getRegisterOnServerLifespan(this);
		
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skip Register;
			} else {
				GCMRegistrar.register(this, Configuration.SENDERID);
			}
		}
		//broadcast to receive gcm id
		BroadcastReceiver receiverRefresh = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				String yourData = intent.getStringExtra("regid");
				if (yourData != null) {
					gcmId = yourData;
					GCMRegistrar.setRegisteredOnServer(context, true);
				}

			}
		};*/
		
		//
		
		updateBirthday();
		btnBirthday.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				DatePickerDialog DPD = new DatePickerDialog(UpdateInforActivity.this,dateSetListener, mYear, mMonth, mDay);
				DPD.show();	
				updateBirthday();
			}
		});
		chkMale.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1){
					chkFemale.setChecked(false);
				}
				else{
					chkFemale.setChecked(true);
				}
			}
		});
		chkFemale.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1){
					chkMale.setChecked(false);
				}
				else{
					chkMale.setChecked(true);
				}
			}
		});
		//register
		btnRegister.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				try {
					imm.hideSoftInputFromWindow(etPass.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etRePass.getWindowToken(), 0);
					imm.hideSoftInputFromWindow(etnickname.getWindowToken(), 0);
					
				} catch (Exception e) {
					// TODO: handle exception
				}
				final String nickname = etnickname.getText().toString();
				//String pass = (etPass.getText().toString());
				 retype = (etRePass.getText().toString());
				StringBuilder birthday = new StringBuilder().append(mYear).append("-").append(mMonth + 1).append("-").append(mDay);
				final String isGender;
				Date now = new Date();
				Integer checkYear = mYear - Integer.parseInt(formatter.format(now));

				if(chkFemale.isChecked()){
					isGender = "0";
				}
				else{
					isGender = "1";
				}
				
					if(nickname.equalsIgnoreCase("")){
					new AlertDialog.Builder(UpdateInforActivity.this)
					.setTitle(getResources().getString(R.string.error))
					.setMessage(getResources().getString(R.string.errornullnicknameregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etnickname, true);
								}
					}).show();
				}
				else if(nickname.length()<6){
					new AlertDialog.Builder(UpdateInforActivity.this)
					.setTitle(getResources().getString(R.string.error))
					.setMessage(getResources().getString(R.string.error6nicknameregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etnickname, true);
								}
					}).show();
				}
				/*else if(retype.length()>0){
						new AlertDialog.Builder(UpdateInforActivity.this)
						.setTitle(getResources().getString(R.string.error))
						.setMessage(getResources().getString(R.string.errornullpassregister))
						.setPositiveButton(getResources().getString(R.string.ok),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										setEditTextFocus(etPass, true);
									}
						}).show();
					}
					else{						//gmail, nickname, gender, birthday,logo, userid
						String[] params = new String[] {nickname,isGender+"",mYear+"-"+mMonth+"-"+mDay,u.getUserId()};
						new AsynRegister().execute(params);
					}
				}*/
				/*else if(retype.length()>0 && retype.length()<6){
					new AlertDialog.Builder(UpdateInforActivity.this)
					.setTitle(getResources().getString(R.string.error))
					.setMessage(getResources().getString(R.string.error6passregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etPass, true);
								}
					}).show();
				}		*/		
				else if(retype.length()>0 && retype.length()<6){
					new AlertDialog.Builder(UpdateInforActivity.this)
					.setTitle(getResources().getString(R.string.error))
					.setMessage(getResources().getString(R.string.error6newpassregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etRePass, true);
								}
					}).show();
				}		
				/*else if(retype.equalsIgnoreCase(pass)){
					new AlertDialog.Builder(UpdateInforActivity.this)
					.setTitle(getResources().getString(R.string.error))
					.setMessage(getResources().getString(R.string.not_the_same_password))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									setEditTextFocus(etRePass, true);
								}
					}).show();
				}	*/
				else if(checkYear>-5){
					new AlertDialog.Builder(UpdateInforActivity.this)
					.setTitle(getResources().getString(R.string.error))
					.setMessage(getResources().getString(R.string.errorbirthdayregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									DatePickerDialog DPD = new DatePickerDialog(UpdateInforActivity.this,dateSetListener, mYear, mMonth, mDay);
									DPD.show();										
								}
					}).show();
				}
				else {
					if(!Utility.isConnect(UpdateInforActivity.this)){
						new AlertDialog.Builder(UpdateInforActivity.this)
						.setTitle(getResources().getString(R.string.titleerrornetwork))
						.setMessage(getResources().getString(R.string.messageerrornetwork))
						.setNegativeButton(getResources().getString(R.string.setting), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								
							}
						})
						.setPositiveButton(getResources().getString(R.string.cancel),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
									}
						}).show();
					}
					else{
						if(retype.equalsIgnoreCase("")){
							String[] params = new String[] {nickname,isGender+"",mYear+"-"+mMonth+"-"+mDay,u.getUserId(),"",""};
							new AsynRegister().execute(params);
						}
						else{
							new DlgPasswordCustom(UpdateInforActivity.this, nickname, isGender+"", mYear+"-"+mMonth+"-"+mDay,u.getUserId(), retype).show();
						}
					}
				}
			}
		});
	}
	class DlgPasswordCustom extends AlertDialog  {
		
		final EditText input;
		String nickname;
		String isGender;
		String time;
		String userID;
		String retype;
		Context context;
		
		@SuppressWarnings("deprecation")
		public DlgPasswordCustom(Context context, String nickname, String isGender, String time, String userID, String retype) {
	        super(context);
	        this.nickname = nickname;
	        this.isGender = isGender;
	        this.time = time;
	        this.userID = userID;
	        this.retype = retype;
	        this.context = context;
	        
	        setTitle(getResources().getString(R.string.hintoldpasswordupdatePlease));
	        // Set an EditText view to get user input 
			 input = new EditText(UpdateInforActivity.this);
			input.setHint(getResources().getString(R.string.hintoldpasswordupdate));
			this.setView(input);
			input.setFocusable(true);
	        setButton(AlertDialog.BUTTON_POSITIVE, "Ok", (new DialogInterface.OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                // this will never be called
	            }
	        }));
	        setButton(AlertDialog.BUTTON_NEGATIVE,"Cancel", new DialogInterface.OnClickListener() {
			  public void onClick(DialogInterface dialog, int whichButton) {
			    return;
			  }
			});
	    }

	    @Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);

	        getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
	            @Override
	            public void onClick(View v) {
	            	 String oldPass = input.getText().toString();
					  if(oldPass.equalsIgnoreCase("")){
						  Toast.makeText(UpdateInforActivity.this, getResources().getString(R.string.errornullpassregister), Toast.LENGTH_LONG).show();
						}
						  else if(oldPass.length()<6){
							  Toast.makeText(UpdateInforActivity.this, getResources().getString(R.string.error6passregister), Toast.LENGTH_LONG).show();
						  }
						  else{
								retype = Utility.md5(retype);
								if(retype.length()>=6)
								oldPass = Utility.md5(oldPass);
								String[] params = new String[] {nickname,isGender,time,userID,oldPass,retype};
								new AsynRegister().execute(params);
						  }
	            }
	        });
	        getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
	            @Override
	            public void onClick(View v) {
	            	Utility.HideKeyboard(context, input);
	            	 dismiss();
	            }
	        });
	    }
	}
	 boolean isClose;
	/*private StartAppAd startAppAd = new StartAppAd(this); 
	@Override 
	public void onResume(){ 
	      super.onResume(); 
	      startAppAd.onResume(); 
	  } 
	@Override 
	  public void onPause() { 
	      super.onPause(); 
	      startAppAd.onPause(); 
	  } 
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		
		if(keyCode==KeyEvent.KEYCODE_HOME){
			 startAppAd.showAd(); 
			    startAppAd.loadAd(); 
		}
		return super.onKeyDown(keyCode, event);
	}*/
	public void setEditTextFocus(EditText et, boolean isFocused)
	{
		et.setCursorVisible(isFocused);
		et.setFocusable(isFocused);
		et.setFocusableInTouchMode(isFocused);

	    if (isFocused) 
	    {
	    	et.requestFocus();
	    }
	    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
	}
	//show keyboard
	public void ShowKeyboard(EditText et)
	{
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
	}
	//
	protected void updateBirthday() {
		tvBirthday.setText(new StringBuilder()
				.append(mDay).append("-").append(mMonth + 1).append("-")
				.append(mYear));
	}
	private OnDateSetListener dateSetListener = new OnDateSetListener() {
		
		@Override
		public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
			mYear = arg1;
			mMonth = arg2;
			mDay = arg3;
			updateBirthday();
		}
	};
	
	
	//asyntask regisster
	class AsynRegister extends AsyncTask<String, Void, String>
	{
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(UpdateInforActivity.this, "",
					getResources().getString(R.string.updating), true);
		}
		@Override
		protected String doInBackground(String... params) {
			return JsonParse.getInstance().updateinfor(params,UpdateInforActivity.this);
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result); 
			progress.dismiss();
			JSONObject json;
			try {
				json = new JSONObject(result);
				String res = json.getString(Config.result);
				if(res.equalsIgnoreCase(Config.norow)){
					AlertDialog.Builder alert = new AlertDialog.Builder(UpdateInforActivity.this);
					alert.setTitle(getResources().getString(R.string.error));
					alert.setMessage(getResources().getString(R.string.alert_error_message_oldpassword));
					alert.setNeutralButton(UpdateInforActivity.this.getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							setEditTextFocus(etPass, true);
						} 
					});
					alert.show();	
				}				
				else{
					JSONObject rjson = json.getJSONArray(Config.result).getJSONObject(0);
					final String gmai = rjson.getString(User.keyGmail);
					final String nickname = rjson.getString(User.keyNickName);
					final String time = rjson.getString(User.keyTime);
					//final String userName = rjson.getString(User.keyUserName);
					String birthday = rjson.getString(User.keyBirthday);
					String type = rjson.getString(User.keyType);
					String gender = rjson.getString(User.keyGender);
					final String userid = rjson.getString(User.keyUserId);
					//String logo = rjson.getString(User.keyLogo);
					User u = new User(userid, "", nickname, gender, birthday, type, gmai, time,"");
					new Database(UpdateInforActivity.this).setUser(u);
					new AlertDialog.Builder(UpdateInforActivity.this)
					.setTitle("")
					.setMessage(getResources().getString(R.string.successtitlerupdate))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {				
									Intent returnIntent = new Intent();
									returnIntent.putExtra("nickname", nickname);
									returnIntent.putExtra("email", gmai);	
									setResult(RESULT_OK, returnIntent);
									finish();									
								}
					}).show();
				}
				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	//get gcm id
	/*class AsynGetGCMID extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params) {
			if(gcm==null){
				//GCMRegistrar.checkManifest(UpdateInforActivity.this);
				gcm = GoogleCloudMessaging.getInstance(UpdateInforActivity.this);
				try {
					gcmId = gcm.register(Configuration.SENDERID);
					Log.d("log","gcm:"+gcmId);
				} catch (IOException e) {
					gcmId = "";
					Log.e("error",e.getMessage());
				}
			}
			return null;
		}
		
	}*/
	
}
